package com.lagou.rpc.provider.server;

import com.lagou.rpc.provider.handler.NettyServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class NettyServer implements DisposableBean {


    @Autowired
    NettyServerHandler nettyServerHandler;

    private  NioEventLoopGroup bossGroup;

    private NioEventLoopGroup wokerGroup;

    public void start(String ip,int port){
        bossGroup = new NioEventLoopGroup();
        wokerGroup = new NioEventLoopGroup();


        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup,wokerGroup)
                    .channel(NioServerSocketChannel.class)
                   .childHandler(new ChannelInitializer<SocketChannel>() {
                       @Override
                       protected void initChannel(SocketChannel socketChannel) throws Exception {
                           ChannelPipeline pipeline = socketChannel.pipeline();
                           pipeline.addLast(new StringDecoder());
                           pipeline.addLast(new StringEncoder());
                           pipeline.addLast(nettyServerHandler);
                       }
                   });

            ChannelFuture bind = serverBootstrap.bind(ip,port);
            System.out.println("服务端启动成功:"+ip+":"+port);
            bind.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if(bossGroup != null){
                bossGroup.shutdownGracefully();
            }
            if(wokerGroup != null){
                wokerGroup.shutdownGracefully();
            }
        }
    }

    @Override
    public void destroy() throws Exception {
        if(bossGroup != null){
            bossGroup.shutdownGracefully();
        }
        if(wokerGroup != null){
            wokerGroup.shutdownGracefully();
        }
    }
}
